What's a Set? Collection with no duplicates (may or may not have order) Does Set have any methods in addition to those in Collection? no new methods are needed Set Interface public interface Set extends Collection { } Why make a new interface with no methods? Why not just implement the Collection interface to make a Set? classes that implement Set will not allow duplicates DEMO (change Collection to Set) HashSet implements Set What can you say about the order of an Iterator on a HashSet? Iterator on HashSet gives the elements in no particular order What's a SortedSet? Collection that has order but no duplicates an Iterator on a SortedSet gives objects in order DEMO (change Set to SortedSet) TreeSet implements SortedSet What can you say about the order of an Iterator on a TreeSet? Iterator on TreeSet gives the elements in compareTo order Does SortedSet have any methods in addition to those in Set? SortedSet Interface public interface SortedSet extends Set { Object first(); Object last(); } HashSet implements Set TreeSet also implements Set Are there any interface-visible differences besides order? theoretically HashSet is constant time theoretically TreeSet is logN time DEMO (compare times for HashSet and TreeSet) What methods must a class implement to be stored in a Collection? When should you implement the toString method? Why? always When should you implement the equals method? Why? essentially always Collection List Set SortedSet ArrayList LinkedList TreeSet HashSet contains and remove need equals to work When should you implement the Comparable interface? Why? SortedSet TreeSet the implementation keeps the elements sorted When should you implement the hashCode method? Why? HashSet HashSet uses hashCode to organize the placement of its elements so they can be added, removed, and found quickly. What are the rules for implementing hashCode? if two objects are ".equals", hashCode must return the same value if two objects are not ".equals", hashCode may return different values if hashCode returns the same value, HashSet will be less efficient Classes in the standard java library already implement these methods. When you write your own classes, you must implement these methods.